<template>
  <div>
    <Toolbar :editor="editorRef" :defaultConfig="toolbarConfig" style="border-bottom:1px solid #eee;" />
    <Editor
      :modelValue="modelValue"
      @update:modelValue="val => emits('update:modelValue', val)"
      :defaultConfig="editorConfig"
      style="min-height:200px;"
      @onCreated="handleCreated"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, watch, onBeforeUnmount } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import '@wangeditor/editor/dist/css/style.css'

const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  }
})
const emits = defineEmits(['update:modelValue'])
const editorRef = ref()
const editorConfig = { placeholder: '请输入内容...' }
const toolbarConfig = {}

watch(() => props.modelValue, (val) => {
  if (editorRef.value && editorRef.value.getHtml() !== val) {
    editorRef.value.setHtml(val || '')
  }
})

const handleCreated = (editor: any) => {
  editorRef.value = editor
}

watch(editorRef, (editor) => {
  if (!editor) return
  editor.on('change', () => {
    emits('update:modelValue', editor.getHtml())
  })
})

onBeforeUnmount(() => {
  if (editorRef.value) editorRef.value.destroy()
})
</script> 